package com.fl.nettydemo.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SelectorServer {
    public static void main(String[] args) {
        try {
            //使用nio 阻塞模式 单线程
            //全局缓存流
            ByteBuffer buffer = ByteBuffer.allocate(32);

            List<SocketChannel> list = new ArrayList<>();
            //开启socket
            ServerSocketChannel socket = ServerSocketChannel.open();
            //将服务器设置为非阻塞模式
            socket.configureBlocking(false);
            //指定服务端端口
            socket.bind(new InetSocketAddress(9999));
            while (true){
                log.info("connect...");
                //获取客户端的信道
                SocketChannel channel = socket.accept();
                //将获取客户端信道设置为非阻塞模式
                channel.configureBlocking(false);
                log.info("connected...,{}",channel);
                list.add(channel);
                for (SocketChannel chl : list) {
                    log.info("before read...,{}",chl);
                    chl.read(buffer);
                    buffer.flip();
                    buffer.clear();
                    log.info("after read...,{}",chl);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
